import React,{useEffect,useState} from "react";
import PubSub from "pubsub-js";

import style from './index.module.css'
const {statisticsBox,statistics,moneyDetails} = style

interface IpriceArr {
    id:string,
    price:number,
    discount:number
}

export default function Statistics(){
    //总价钱
    const [price,setPrice] = useState(0)
    //会员能优惠多少钱
    const [discount,setDiscount] = useState(0)


    useEffect(() => {
        let priceArr:IpriceArr[] =[]

        const pub = PubSub.subscribe('price',(message,data:IpriceArr)=>{
            //通过 _id 分辨是哪个商品
            //如果数组已经有这个传递来的商品了 就将最新的价格更新到数组对应的商品里里 没有就将商品添加到数组里
            if(priceArr.some(item=>item.id === data.id)){
                for(let item of priceArr){
                    if(item.id === data.id){
                        item.price = data.price
                        break
                    }
                }
            }else{
                priceArr.push(data)
            }

            //计算所有商品的总价
            let TotalPrice:number=0

            //总折扣减掉的钱
            let TotalDiscount = 0

            priceArr.forEach(item=>{
                TotalPrice += item.price
                TotalDiscount += Math.floor((10 - item.discount) / 10 * item.price * 100)/100
            })
            
            //保留两位小数
            setPrice(Math.floor(TotalPrice * 100)/100)

            setDiscount(Math.floor(TotalDiscount * 100)/100)

            PubSub.publish('memberDiscount',Math.floor(TotalDiscount * 100)/100)
        })
        
        return () => {
            PubSub.unsubscribe(pub)
        }
    }, [])


    return (
        <div className={statisticsBox}>
            <ul className={statistics}>
                <li>
                    <div>商品总价</div>
                    <div className={moneyDetails}>
                        <span>¥</span>
                        <span>{price}</span>
                    </div>
                </li>
                <li>
                    <div>活动优惠</div>
                    <div className={moneyDetails}>
                        <span>-¥</span>
                        <span>{discount}</span>
                    </div>
                </li>
                <li>
                    <div>配送费</div>
                    <div>包邮</div>
                </li>
                <li>
                    <div>商品实付</div>
                    <div className={moneyDetails}>
                        <span>¥</span>
                        <span>{Math.floor((price - discount) * 100)/100}</span>
                    </div>
                </li>
                <div>
                    <span>合计</span>
                    <span>¥</span>
                    <span>{Math.floor((price - discount) * 100)/100}</span>
                </div>
            </ul>
        </div>
    )
}